package com.dingwen.sprboojwtstu.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Map;
import java.util.Optional;

/**
 * JWT 工具类
 *
 * @author dingwen
 * 2021.05.31 11:39
 */
public class JwtUtil {
    /**
     * 秘密密钥
     */
    private static final String SECRET_KEY = "!qaz@wsx";

    /**
     * 过期时间单位
     */
    public static final int unit = Calendar.MINUTE;

    /**
     * 过期时间量
     */
    public static final int amount = 30;

    /**
     * 创建jwt牌
     *
     * @param payload 有效载荷
     * @return {@link String}
     */
    public static String createJwtToken(Map<String, Object> payload) {
        // payload
        Optional.ofNullable(payload).orElseThrow(() -> new RuntimeException("jwt payload not null"));
        // 过期时间
        Calendar calendar = Calendar.getInstance();
        calendar.add(unit, amount);

        return JWT.create()
                .withClaim("payload", payload)
                .withExpiresAt(calendar.getTime())
                .sign(Algorithm.HMAC256(SECRET_KEY));
    }


    /**
     * 验证
     *
     * @param jwtToken jwt令牌
     * @return {@link DecodedJWT}
     */
    public static DecodedJWT verify(String jwtToken) {
        return JWT.require(Algorithm.HMAC256(SECRET_KEY)).build().verify(jwtToken);
    }

    /**
     * 得到有效载荷
     *
     * @param jwtToken jwt令牌
     * @return {@link Map<>}
     */
    public static Map<String, Object> getPayload(String jwtToken) {
        DecodedJWT decodedJWT = verify(jwtToken);
        return decodedJWT.getClaim("payload").asMap();
    }

}
